<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisbl=true">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 角色列表区域 -->
    <el-table :data="rolesList" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['bdbuttom',i1===0?'bdtop':'','vcenter']"
            v-for="(item1,i1) in scope.row.children"
            :key="item1.id"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="removeById(scope.row,item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级三级权限 -->
            <el-col :span="19">
              <!-- 通过for循环嵌套渲染二级权限 -->
              <el-row
                :class="[i2===0?'':'bdtop','vcenter']"
                v-for="(item2,i2) in item1.children"
                :key="item2.id"
              >
                <el-col :span="6">
                  <el-tag
                    closable
                    @close="removeById(scope.row,item2.id)"
                    type="success"
                  >{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    closable
                    @close="removeById(scope.row,item3.id)"
                    type="warning"
                    v-for="(item3,i3) in item2.children"
                    :key="item3.id"
                  >{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <pre></pre>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column typr="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button
            @click="showEdit(scope.row.id)"
            size="mini"
            type="primary"
            icon="el-icon-edit"
          >编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="dele(scope.row.id)">删除</el-button>
          <el-button @click="showSetRight(scope.row)" size="mini" type="warning" icon="el-icon-setting"
          >分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisbl" width="50%" @close="addDialogClosed">
      <!-- 添加用户内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
        <!-- 底部区 -->
        <el-form-item>
          <el-button @click="addDele">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="EditDialog" width="50%" @close="editDialogClosed">
      <!-- 编辑用户内容主体区 -->
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
        <!-- 底部区 -->
        <el-form-item>
          <el-button @click="editDele">取 消</el-button>
          <el-button type="primary" @click="EditUser">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="setRightdialogVisible" width="50%"
     @close="setRightdialogClose"
    >
     <!-- 树形控件 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id"
      default-expand-all :default-checked-keys="defKeys" ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Rolves",
  data() {
    return {
      //所有角色列表数据
      rolesList: [],
      //
      addDialogVisbl: false,
      //
      EditDialog: false,
      //添加/编辑角色内容
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      //
      editForm: {
        roleId: "",
        roleName: "",
        roleDesc: ""
      },
      //验证规则
      addFormRules: {
        roleName: [
          { required: true, message: "请输角色名称", trigger: "blur" },
          { min: 2, max: 7, message: "长度在 2 到 7 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输角色描述", trigger: "blur" },
          { min: 2, max: 7, message: "长度在 2 到 7 个字符", trigger: "blur" }
        ]
      },
      //控制分配权限对话框setRightdialogVisible
      setRightdialogVisible:false,
      //所有权限的数据
      rightsList:[],
      //树形控件属性绑定对象
      treeProps: {
          children: 'children',
          label: 'authName'    
      },
      //默认选中的id数组
     defKeys:[],
     //当前即将分配权限的角色id
     roleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
      //   console.log(this.rolesList);
    },
    // 取消添加角色
    addDialogClosed() {
      return this.$refs.addFormRef.resetFields();
    },
    //添加管理角色
    addUser() {
      this.$refs.addFormRef.validate(async vaild => {
        if (!vaild) return;
        const { data: res } = await this.$http.post("roles", this.addForm);
        if (res.meta.status !== 201)
          return this.$message.error("创建管理角色失败");
        this.addDialogVisbl = false;
        this.getRolesList();
      });
    },
    //取消清空添加角色
    addDele() {
      this.$refs.addFormRef.resetFields();
      this.addDialogVisbl = false;
    },
    //展示编辑角色
    async showEdit(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询失败");
      }
      this.editForm = res.data;
      console.log(this.editForm.roleName);
      console.log(this.editForm.roleDesc);
      this.EditDialog = true;
    },
    //确定修改管理角色
    EditUser() {
      this.$refs.editFormRef.validate(async vaild => {
        if (!vaild) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败");
        }
        //关闭对话框
        this.EditDialog = false;
        //刷新列表
        this.getRolesList();
        //提示修改成功
        this.$message.success("修改用户成功");
      });
    },
    //
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //取消清空修改编辑
    editDele() {
      this.$refs.editFormRef.resetFields();
      this.EditDialog = false;
    },
    async dele(id) {
      // console.log(id);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") return this.$message.info("取消删除");
      console.log(confirmResult);
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.getRolesList();
      this.$message.success("删除成功");
    },
    //删除对应的权限
    async removeById(role, right) {
      //弹框提示
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") return this.$message.info("取消删除");
      // console.log(right);
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${right}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除权限失败");
      this.$message.success("删除权限成功");
      role.children = res.data;
    },
    async showSetRight(role) {
        this.roleId = role.id
        //获取所有权限的数据
        const {data:res} = await this.$http.get('rights/tree')
        
        if(res.meta.status!==200) return this.$message.error('获取权限数据失败')
        //把获取到的权限数据保存在data中
        this.rightsList = res.data
        //递归获取三级节点的ID
        this.getLeafKey(role,this.defKeys)
        console.log(this.rightsList);
        this.setRightdialogVisible=true
    },
    //通过递归形式获取角色项并保存到defKeys数组中
    getLeafKey(node,arr){
        //如果当前节点没有children属性，则是三级节点
        if(!node.children){
            return arr.push(node.id)
        }
        node.children.forEach(item=>{
            this.getLeafKey(item,arr)
        })
    },
    //监听分配权限对话框的关闭权限
    setRightdialogClose(){
        this.defKeys=[]
    },
    //为角色分配权限
    async allotRights(){
        const keys = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ] 
        console.log(keys);
        const idStr = keys.join(',')
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status!==200){
            return this.$message.error('分配权限成功')
        }
        //重新刷新数据
        this.getRolesList();
        this.$message.success('分配权限成功')
        this.setRightdialogVisible = false
    }
  }
};
</script>


<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbuttom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
